﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LeadVinaglue.Models;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Utility;
using LeadVinaglue.Helpers;

namespace LeadVinaglue.Repository
{
    public class BaseRepository
    {
        LeadVinaglueEntities entities = new LeadVinaglueEntities();
        string BannerImageUrl = "/Upload/Banners";       

        public List<NavigationMenu> GetMenuConfig(string pageType)
        {
            List<NavigationMenu> list = new List<NavigationMenu>();
            NavigationConfig stateConfig = new NavigationConfig();
            NavigationConfig categoryConfig=new NavigationConfig();
            NavigationMenu model;

            // Get 2 configs
            // Caching process
            // 1: State caching
            string StateCachingMenuConfig = "StateListConfig";
            int StateCachingMenuTimer = 10;
            if (HttpContext.Current.Cache[StateCachingMenuConfig] != null)
                stateConfig = (NavigationConfig)HttpContext.Current.Cache[StateCachingMenuConfig];
            if (HttpContext.Current.Cache[StateCachingMenuConfig] == null)
            {
                stateConfig = LeadTools.Deserialize(System.Web.HttpContext.Current.Server.MapPath(@"/Configs/StateListConfig.xml"), stateConfig);
                HttpContext.Current.Cache.Insert(StateCachingMenuConfig, stateConfig, null, DateTime.Now.AddMinutes(StateCachingMenuTimer), TimeSpan.Zero);
            }

            // 2: Category caching
            string CategoryCachingMenuConfig = "CategoryListConfig";
            int CategoryCachingMenuTimer = 10;
            if (HttpContext.Current.Cache[CategoryCachingMenuConfig] != null)
                categoryConfig = (NavigationConfig)HttpContext.Current.Cache[CategoryCachingMenuConfig];
            if (HttpContext.Current.Cache[CategoryCachingMenuConfig] == null)
            {
                categoryConfig = LeadTools.Deserialize(System.Web.HttpContext.Current.Server.MapPath(@"/Configs/CategoryListConfig.xml"), categoryConfig);
                HttpContext.Current.Cache.Insert(CategoryCachingMenuConfig, categoryConfig, null, DateTime.Now.AddMinutes(CategoryCachingMenuTimer), TimeSpan.Zero);
            }


            // Add items
            // Home page
            model = new NavigationMenu();
            model.LinkText="Trang chủ";
            model.LinkUrl="/";
            model.IsCurrentTab = (pageType == LeadConstant.HOME) ? true : false;
            list.Add(model);

            // Zone
            model = new NavigationMenu();
            model.LinkText = "Khu vực";
            model.LinkUrl = "/tat-ca-khu-vuc";
            model.IsCurrentTab = (pageType == LeadConstant.ZONE) ? true : false;
            model.SubMenu = GetStateMenu(stateConfig);
            list.Add(model);

            // Category
            model = new NavigationMenu();
            model.LinkText = "Danh mục";
            model.LinkUrl = "/tat-ca-danh-muc";
            model.IsCurrentTab = (pageType == LeadConstant.CATEGORY) ? true : false;
            model.TabName = "subcat";
            model.SubMenu = GetCategoryMenu(categoryConfig);
            list.Add(model);

            // Business
            model = new NavigationMenu();
            model.LinkText = "Doanh nghiệp";
            model.LinkUrl = "/doanh-nghiep";
            model.IsCurrentTab = (pageType == LeadConstant.BUSINESS) ? true : false;
            list.Add(model);

            // Product Special
            model = new NavigationMenu();
            model.LinkText = "Tin đặc biệt";
            model.LinkUrl = "/raovat/dacbiet";
            model.IsCurrentTab = (pageType == LeadConstant.PRODUCTSPECIAL) ? true : false;
            list.Add(model);

            return list;
        }

        public List<NavigationMenu> GetMenuConfigTLVN(string pageType)
        {
            List<NavigationMenu> list = new List<NavigationMenu>();
            NavigationConfig MenuConfig = new NavigationConfig();
            NavigationMenu model = new NavigationMenu();

            string StateCachingMenuConfig = "MenuConfig";
            int StateCachingMenuTimer = 10;
            if (HttpContext.Current.Cache[StateCachingMenuConfig] != null)
                MenuConfig = (NavigationConfig)HttpContext.Current.Cache[StateCachingMenuConfig];
            if (HttpContext.Current.Cache[StateCachingMenuConfig] == null)
            {
                MenuConfig = LeadTools.Deserialize(System.Web.HttpContext.Current.Server.MapPath(@"/Configs/MenuConfig.xml"), MenuConfig);
                HttpContext.Current.Cache.Insert(StateCachingMenuConfig, MenuConfig, null, DateTime.Now.AddMinutes(StateCachingMenuTimer), TimeSpan.Zero);
            }
            List<NavigationLink> listNavigationLink = new List<NavigationLink>();

            // Check conditions
            if (MenuConfig != null && MenuConfig.NavigationItems != null && MenuConfig.NavigationItems.Count > 0)
            {
                foreach (var item in MenuConfig.NavigationItems)
                {
                    model = new NavigationMenu();
                    model.LinkText = item.ItemName;
                    model.LinkUrl = item.ItemLink;
                    model.IsCurrentTab = (pageType == LeadConstant.ZONE) ? true : false;
                    if(item.SubItems != null)
                    {                        
                        List<NavigationLink> ListNavigationLink = new List<NavigationLink>();
                        for (int j = 0; j < item.SubItems.Count; j++)
                        {
                            NavigationLink ItemNavigationLink = new NavigationLink();
                            ItemNavigationLink.LinkText = item.SubItems[j].ItemName;
                            ItemNavigationLink.LinkUrl = item.SubItems[j].ItemLink;
                            ListNavigationLink.Add(ItemNavigationLink);
                        }
                        model.SubMenu = ListNavigationLink;
                    }
                    list.Add(model);
                }
            }            
            return list;
        }

        public List<CategoryModel> GetCategories()
        {
            CategoryRepository repository = new CategoryRepository();

            return repository.GetAll();
        }
        
        public List<NavigationLink> GetAllProductSpecial(int take)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            var items = (from c in entities.Products
                         where c.Active == true
                         select new
                         {
                             ID = c.ID,
                             Title = c.Title
                         });

            // Add items to list
            foreach (var item in items)
            {
                NavigationLink model = new NavigationLink();
                model.LinkText = item.Title;
                model.LinkUrl = string.Format("/raovat/d{0}/{1}", item.ID, StringClearFormat.ClearSpecials(item.Title));
                list.Add(model);
            }

            return list;
        }

        public List<NavigationLink> GetAllProductTop(int take)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            var items = (from c in entities.Products
                         where c.Active == true
                         orderby c.ID descending
                         select new
                         {
                             ID = c.ID,
                             Title = c.Title
                         });

            // Add items to list
            foreach (var item in items)
            {
                NavigationLink model = new NavigationLink();
                model.LinkText = item.Title;
                model.LinkUrl = string.Format("/raovat/d{0}/{1}", item.ID, StringClearFormat.ClearSpecials(item.Title));
                list.Add(model);
            }

            return list;
        }

        public List<NavigationLink> GetAdvNotification(int take)
        {
            List<NavigationLink> list = new List<NavigationLink>();
            var items = (from c in entities.Banners
                         where c.Active == true && c.StartDate <= DateTime.Now && c.EndDate >= DateTime.Now && c.ImageURL == "" && c.FlashURL == ""
                         orderby c.ID descending
                         select new
                         {
                             ID = c.ID,
                             Title = c.Title,
                             WebsiteUrl = c.WebsiteUrl
                         });

            // Add items to list
            foreach (var item in items)
            {
                NavigationLink model = new NavigationLink();
                model.LinkText = item.Title;
                model.LinkUrl = item.WebsiteUrl;
                list.Add(model);
            }

            return list;
        }

        #region Build Menu
        private List<NavigationLink> GetCategoryMenu(NavigationConfig config)
        {
            List<NavigationLink> list = new List<NavigationLink>();

            // Check conditions
            if (config != null && config.NavigationItems != null && config.NavigationItems.Count > 0)
            {
                foreach (var item in config.NavigationItems)
                {
                    NavigationLink link = new NavigationLink();
                    link.LinkText = item.ItemName;
                    link.LinkUrl = item.ItemLink;

                    list.Add(link);
                }
            }

            return list;
        }
        private List<NavigationLink> GetStateMenu(NavigationConfig config)
        {
            List<NavigationLink> list = new List<NavigationLink>();

            // Check conditions
            if (config != null && config.NavigationItems != null && config.NavigationItems.Count > 0)
            {
                foreach (var item in config.NavigationItems.Where(c => c.IsTop == true))
                {
                    NavigationLink link = new NavigationLink();
                    link.LinkText = item.ItemName;
                    link.LinkUrl = item.ItemLink;
                    link.IsTop = item.IsTop;

                    list.Add(link);
                }
                foreach (var item in config.NavigationItems.Where(c => c.IsTop == false).OrderBy(c => c.ItemName))
                {
                    NavigationLink link = new NavigationLink();
                    link.LinkText = item.ItemName;
                    link.LinkUrl = item.ItemLink;
                    link.IsTop = item.IsTop;

                    list.Add(link);
                }
            }

            return list;
        }
        #endregion

        public void GetAdScripts(BaseModel model, string pageType)
        {
            List<BannerModel> filters = GetBanners(pageType);

            if (filters != null && filters.Count > 0)
            {
                // Sky Ads
                model.SkyAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.SKY).ToList(), "skypAds");

                // Lead/Middle Ads
                model.LeadAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.LEADERBOARD).ToList(), "leadAds");

                // Bottom Ads
                model.BottomAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.BOTTOM).ToList(), "btmAds");

                // Popup Ads
                model.PopupAdScripts = BuildSkyAdScripts(filters.Where(c => c.PositionId == PositionConstant.POPUP).ToList(), "popAds");
                
                // TowerAds
                var list = filters.Where(c => c.PositionId == PositionConstant.TOWER).ToList();

                if (list!=null)
                {
                    if (list.Count >= 16)
                    {
                        for (int i = 1; i <= 6; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 3).Take(3).ToList(), string.Format("TAZone{0}", i));
                        }
                    }
                    else if (list.Count >= 11)
                    {
                        for (int i = 1; i <= 6; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 2).Take(2).ToList(), string.Format("TAZone{0}", i));
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= list.Count; i++)
                        {
                            model.TowerAdScripts += BuildSkyAdScripts(list.Skip((i - 1) * 1).Take(1).ToList(), string.Format("TAZone{0}", i));
                        }
                    }

                }

            }
        }

        #region Build Ads
        private List<BannerModel> GetBanners(string pageType)
        {
            List<BannerModel> list=new List<BannerModel>();

            var items = (from c in entities.Banners
                    where c.Active && c.StartDate <= DateTime.Now && c.EndDate >= DateTime.Now
                    select c);

            switch (pageType)
            {
                case LeadConstant.HOME:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnHomePage == true);
                        break;
                    }
                case LeadConstant.CATEGORY:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnCategoryPage == true);
                        break;
                    }
                case LeadConstant.ZONE:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnZonePage == true);
                        break;
                    }
                case LeadConstant.PRODUCTINFO:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnDetailPage == true);
                        break;
                    }
                default:
                    {
                        items = items.Where(c => c.ShowAllPages == true || c.ShowOnOtherPage == true);
                        break;
                    }
            }

            // Add items
            foreach (var item in items.OrderByDescending(c => c.ID))
            {
                BannerModel model = new BannerModel();

                model.ID = item.ID;
                model.GroupId = item.GroupID;
                model.PositionId = item.PositionID;
                model.Title = item.Title;
                model.ImageUrl = item.ImageURL;
                model.FlashUrl = item.FlashURL;
                model.WebsiteUrl = item.WebsiteUrl;
                model.Width = Convert.ToInt32(item.Width);
                model.Height = Convert.ToInt32(item.Height);
                model.Active = item.Active;

                list.Add(model);
            }

            return list;
        }

        private string BuildSkyAdScripts(List<BannerModel> list, string skyName)
        {
            string script = string.Empty;

            if (list != null && list.Count > 0)
            {
                script = "<script language=\"javascript\" type=\"text/javascript\">";
                script += string.Format("{0} = new Banner('{1}');", skyName, skyName); 

                int i = 0;
                foreach (var item in list)
                {
                    i++;
                    if (!string.IsNullOrEmpty(item.FlashUrl))
                    {
                        if (!string.IsNullOrEmpty(item.WebsiteUrl))
                            script += string.Format("{0}.add(\"FLASH\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.FlashUrl), i, item.Height, item.Width, item.WebsiteUrl);
                        else
                            script += string.Format("{0}.add(\"FLASH\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.FlashUrl), i, item.Height, item.Width, "##");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(item.WebsiteUrl))
                            script += string.Format("{0}.add(\"IMAGE\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.ImageUrl), i, item.Height, item.Width, item.WebsiteUrl);
                        else
                            script += string.Format("{0}.add(\"IMAGE\", '{1}', {2}, {3}, {4}, \"{5}\", \"_blank\");", skyName, string.Format("{0}/{1}", BannerImageUrl, item.ImageUrl), i, item.Height, item.Width, "##");
                    }
                }

                script += string.Format("document.write({0});", skyName);
                script += string.Format("{0}.start();", skyName);
                script += "</script>";
            }

            return script;
        }

        #endregion
    }

}